﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using InstrumentCheck.Module;
using InstrumentCheck.BLL;
using InstrumentCheck.ILocalService;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace InstrumentCheck.WebUI
{
    public partial class CorrectItem : BasePage
    {
        User UserInfo = null;
        private static WorkflowRuntime runtime;
        private static WorkflowInstance instance;
        private static ExternalDataExchangeService service;
        private static WorkflowPersistenceService perService;
        private static FormService formService;

        protected void Page_Load(object sender, EventArgs e)
        {
            UserInfo = Session["UserInfo"] as User;
            if (!Page.IsPostBack)
            {
                ViewState["ID"] = Request["ID"];
                InitialWorkFlow();

                if (ViewState["ID"] == null)
                    ShowPageValue();
                else
                    ShowPageValueWithID(int.Parse(ViewState["ID"].ToString()));
            }
        }

        private void InitialWorkFlow()
        {
            runtime = new WorkflowRuntime();
            service = new ExternalDataExchangeService();
            formService = new FormService();
            perService = new SqlWorkflowPersistenceService(System.Configuration.ConfigurationManager.ConnectionStrings["PersistenceString"].ConnectionString);
            if (runtime.GetService(service.GetType()) == null)  //服务不能重复加入
                runtime.AddService(service);

            if (runtime.GetService(perService.GetType()) == null)
                runtime.AddService(perService);

            if (service.GetService(formService.GetType()) == null) //加入外部数据交换服务
                service.AddService(formService);

            runtime.WorkflowIdled += OnWorkflowIdled;  //工作流闲置事件
            runtime.StartRuntime();
        }

        public void OnWorkflowIdled(object sender, WorkflowEventArgs e)
        {
            e.WorkflowInstance.TryUnload();   //将内存数据持久化到数据库中
        }        
        
        private void ShowPageValue()
        {
            divFlowDesc.Style.Add("display", "none");
            Session["FlowNO"] = 0;
            lblFormNO.Text = "Auto Number";
            lblCreaterInfo.Text = UserInfo.EmpChineseName + " - " + UserInfo.DeptNO + " - " + UserInfo.ExtNO;
            lblApplicant.Text = UserInfo.EmpChineseName + " - " + UserInfo.ExtNO;
            txtApplicantNO.Text = UserInfo.EmpNO;
            lblApplyDept.Text = UserInfo.DeptNO;
            lblApplyDate.Text = DateTime.Today.ToString("yyyy/MM/dd");
            imgSend.Visible = true;
            imgSave.Visible = true;
        }

        private void ShowPageValueWithID(int ID)
        {
            ApplyForm form = Form_bll.GetFormDetailByID(ID);
        }

        protected void imgSend_Click(object sender, ImageClickEventArgs e)
        {
            //产生form的资料并保存到DB
            //try
            //{
            //    instance = runtime.CreateWorkflow(typeof(InstrumentCheck.WorkFlow.Workflow1));
            //    instance.Start();
            //    ApplyForm form = GenerateForm();
            //    FormRouting routing = GenerateRouting();
            //    FormApproveEvntArgs eventArgs = new FormApproveEvntArgs(instance.InstanceId, form, routing);
            //    formService.RaiseStaffSubmitEvent(eventArgs);
            //}
            //catch
            //{
            //    throw;
            //}
        }

        private ApplyForm GenerateForm()
        {
            Item item = new Item();
            item.AssetNO = txtAssetNO.Text.Trim();
            item.AssetType = (AssetType)int.Parse(ddlAssetType.SelectedItem.Value);
            item.PRNO = txtPRNO.Text.Trim();
            item.BuyDate = Convert.ToDateTime(txtBuyDate.Text.Trim());

            if (ddlBuyCurrency.SelectedIndex != 0)  //购买币别
                item.CurrencyType = (CurrencyType)Enum.Parse(typeof(CurrencyType), ddlBuyCurrency.SelectedItem.Value);
            
            if(txtBuyAmount.Text.Trim() != "")   //购买金额
                item.BuyAmount = Convert.ToDouble(txtBuyAmount.Text.Trim());

            item.FirstCorrectTime = Convert.ToDateTime(txtFirstCorrectDate.Text.Trim());

            if(ddlCorrectCurrency.SelectedIndex != 0) //校验币别
                item.CorrectCurrencyType = (CurrencyType)Enum.Parse(typeof(CurrencyType), ddlCorrectCurrency.SelectedItem.Value);
            item.CorrectAmount = int.Parse(txtCorrectAmount.Text.Trim());  //校验费用

            item.NeedCorrectDate = Convert.ToDateTime(txtNeedCorrectDate.Text.Trim());
            item.CorrectCycle = (CorrectCycle)int.Parse(ddlCorrectCycle.SelectedItem.Value);
            item.CurrentStatus = (AssetStatus)int.Parse(ddlCurrentStatus.SelectedItem.Value);
            item.CorrectType = (CorrectType)int.Parse(ddlCorrectType.SelectedItem.Value);
            item.Standard = txtStandard.Text.Trim();
            item.Remark = txtRemark.Text.Trim();

            item.ItemAttachment = new List<Attach>();
            AddAttachment(item, txtAttachInfo.Text.Trim().Split(';'), AttachmentType.Attachment);
            AddAttachment(item, txtImageInfo.Text.Trim().Split(';'), AttachmentType.Picture);

            ApplyForm form = new ApplyForm();
            User applicant = new User();
            applicant.EmpNO = txtApplicantNO.Text;
            form.Applicant = applicant;
            form.ApplyDate = DateTime.Now;
            form.ApplyReason = txtApplyReason.Text.Trim();

            form.Creater = UserInfo;

            form.FormNO = 0;
            if (chkNew.Checked)
                form.FormType = FormType.New;
            else if (chkModify.Checked)
                form.FormType = FormType.Change;
            form.Item = item;
            form.instanceID = instance.InstanceId;
            form.FormStatus = FormStatus.Processing;

            return form;
        }

        private void AddAttachment(Item item,string[] aryAttach,AttachmentType type)
        {
            
            foreach (string str in aryAttach)
            {
                string[] strAttach = str.Split('~');
                if (strAttach[0] == "")
                    break;
                Attach attach = new Attach();
                int intFormNO;
                int.TryParse(lblFormNO.Text.Trim(), out intFormNO);
                attach.FormNO = intFormNO;
                attach.SystemName = strAttach[0];
                attach.ClientName = strAttach[1];
                attach.Type = type;
                item.ItemAttachment.Add(attach);
            }
            
        }

        private FormRouting GenerateRouting()
        {
            FormRouting routing = new FormRouting();
            routing.FlowNO = 0;
            return routing;
        }

        //private void SendMail(ApplyForm form,FormRouting routing)
        //{
        //    // 需要根据routing的FlowNO找到下一关需要发送的mail人员邮件地址
        //    string strMailBody = Form_bll.GenerateMailBody(form);
        //    MailAddress mailFrom = new MailAddress(UserInfo.Email);
        //    List<MailAddress> list = Form_bll.GetNextFlowMailAddress(routing);
        //    string strSubject = "";
        //    switch (form.FormStatus)
        //    {
        //        case FormStatus.Processing:
        //            strSubject = "單別 = 校驗申請單：單號 = " + form.FormNO.ToString("0000000000") + "簽核通知";
        //            break;
        //        case FormStatus.Agree:
        //        case FormStatus.Disagree:
        //        case FormStatus.WithDraw:
        //            strSubject = "[通知] 校驗申請單： 單號 = " + form.FormNO.ToString("0000000000");
        //            break;
        //    }
            
        //    PublicFunction.SendMail(mailFrom, list.ToArray(), null, strSubject, strMailBody, null);
        //}
    }
}
